/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var haveOnChangeError = false;
var captCheck;
window.onload = function(){
    loadCaptchaString()
   
}
function loadCaptchaString(){
    var xmlhttp;
    var data="action=getCaptcha";
    xmlhttp=getXmlHttpObj();
    xmlhttp.open("GET", contextPath+"/CaptchaServlet?"+data, false);
    xmlhttp.send();
    captCheck = xmlhttp.responseText;
}

function saveNewAccount(){
    try{
        var container = document.getElementById ("page-container");
        var textboxes= container.querySelectorAll("input");
        haveOnChangeError = false;
        loadCaptchaString();
        for (i = 0; i < textboxes.length; i++) {
            var tbox=textboxes[i];
            if(tbox.id!="home-username" && tbox.id!="home-password" && tbox.id!="home-login-button"){
                validateInput(tbox);
            }
        }
        if(!haveOnChangeError){
            var xmlhttp;
            var username = document.getElementById("txtUsername");
            var password = document.getElementById("txtPassword");
            var email = document.getElementById("txtEmail");
            var firstName = document.getElementById("txtFirstName");
            var lastName = document.getElementById("txtLastName");
            var province = document.getElementById("txtCity");
            var district = document.getElementById("txtDistrict");
            var address = document.getElementById("txtAddress");
            var phoneNum = document.getElementById("txtPhoneNum");
        
            var data = "action=Add_Account&username=" + username.value
            + "&password=" + password.value
            + "&email=" + email.value
            + "&firstName=" + firstName.value
            + "&lastName=" + lastName.value
            + "&province=" + province.value
            + "&district=" + district.value
            + "&address=" + address.value
            + "&phoneNum=" + phoneNum.value
        
            xmlhttp = getXmlHttpObj();
            xmlhttp.open("POST", contextPath + "/UserController?"+data, true);
            xmlhttp.send();
            xmlhttp.onreadystatechange=function(e){
                var current = e.target;
                if (current.readyState==4 && current.status==200)
                {
                    var result=current.responseText;
                    var message = document.getElementById("submit-registry-message");
                    message.innerHTML="";
        
                    if(result == "Done"){
                        message.innerHTML="registered successfully".fontcolor("green");
                        for (i = 0; i < textboxes.length; i++) {
                            var tbox=textboxes[i];
                            if(tbox.id!="home-username" && tbox.id!="home-password" && tbox.id!="home-login-button"){
                                tbox.value="";
                            }
                        }
                        document.getElementById("reg-understand").checked = false;
                    }else{
                        message.innerHTML=result.fontcolor("red");
                    }
                }
            }
        }
    }catch(error){     
    }
}

function validateInput(current){
    var id = current.id;
    if(id=="txtUsername"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9]{1,20})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            });
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character";
                err.innerHTML=message;
            });
        var xmlhttp;
        var data = "action=Check_UserName&username=" + current.value;
        xmlhttp=getXmlHttpObj();
        xmlhttp.open("GET",contextPath+"/UserController?"+data,false);
        xmlhttp.send();
        var resString=xmlhttp.responseText;
        if(resString == "true"){
            haveOnChangeError = true;
            var eContainer=document.getElementById(id+"Validation");
            eContainer.innerHTML="Name has already exist";
        }
    }else if(id=="txtPassword"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9]{6,40})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            });
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character";
                err.innerHTML=message;
            });
    }else if(id=="txtRepassword"){

        var password = document.getElementById("txtPassword");
        var reRassword = document.getElementById(id);
        if(reRassword.value != password.value){
            haveOnChangeError = true;
            var eContainer=document.getElementById(id+"Validation");
            eContainer.innerHTML="Password is not match";
        } else {
            document.getElementById(id+"Validation").innerHTML="";
        }
    }else if(id=="txtEmail"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{1,4})+$"
            ,function(err){
                haveOnChangeError = true;
                var message="Email invalid";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
    }else if(id=="txtReemail"){
        var email = document.getElementById("txtEmail");
        var reEmail = document.getElementById(id);
        if(email.value != reEmail.value){
            haveOnChangeError = true;
            var eContainer=document.getElementById(id+"Validation");
            eContainer.innerHTML="Email is not match";
        } else {
            document.getElementById(id+"Validation").innerHTML="";
        }
    }
    else if(id=="txtFirstName"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]{1,20})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character";
                err.innerHTML=message;
            }
            );
    }else if(id=="txtLastName"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]{1,20})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character";
                err.innerHTML=message;
            }
            );
    }
    else if(id=="txtCity"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]{1,20})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character";
                err.innerHTML=message;
            }
            );
    }else if(id=="txtDistrict"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]{1,20})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9 ]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character";
                err.innerHTML=message;
            }
            );
    }
    else if(id=="txtAddress"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9./# ]{1,30})?$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([a-zA-Z0-9./# ]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Cannot empty or has specific character except: ./#";
                err.innerHTML=message;
            }
            );
    }
    else if(id=="txtPhoneNum"){
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([0-9]+){8,12}$"
            ,function(err){
                haveOnChangeError = true;
                var message="Out of range";
                err.innerHTML=message;
            },function(err){
                var message="";
                err.innerHTML=message;
            }
            );
        new Validator(current
            , document.getElementById(id+"Validation")
            , "^([0-9]+)$"
            ,function(err){
                haveOnChangeError = true;
                var message="Digit only ex:39306666<br/>0913555666<br/>01275556666";
                err.innerHTML=message;
            }
            );
    } else if(id=="txtcaptcha"){
        var cap = document.getElementById("txtcaptcha");
        if(cap.value != captCheck){
            haveOnChangeError = true;
            var eContainer=document.getElementById(id+"Validation");
            eContainer.innerHTML="Captcha is not match";
        } else {
            document.getElementById(id+"Validation").innerHTML="";
        }
    } else if(id=="reg-understand"){
        var regValue = document.getElementById(id);
        if(regValue.checked != true){
            haveOnChangeError = true;
            var eContainer=document.getElementById(id+"Validation");
            eContainer.innerHTML="You must tick the agree node";
        } else {
            document.getElementById(id+"Validation").innerHTML="";
        }
    }
    showError(haveOnChangeError, id);
}

function showError(haveOnChangeError, id){
    var validationId= id + "Validation";
    document.getElementById(validationId).style.visibility = (!!haveOnChangeError)?"visible":"hidden";
}

function Validator(pInput,pErrorContainer,pPattern,onError,onSuccess){
    var reg=new RegExp(pPattern);
    if(reg.test(convertToUnsign(pInput.value))){
        if (onSuccess && typeof(onSuccess) === "function") {
            onSuccess(pErrorContainer);
        }
    }else{
        if (onError && typeof(onError) === "function") {
            onError(pErrorContainer);
        }
    }
}

function convertToUnsign(input){
    var signedChars     = "àảãáạăằẳẵắặâầẩẫấậđèẻẽéẹêềểễếệìỉĩíịòỏõóọôồổỗốộơờởỡớợùủũúụưừửữứựỳỷỹýỵÀẢÃÁẠĂẰẲẴẮẶÂẦẨẪẤẬĐÈẺẼÉẸÊỀỂỄẾỆÌỈĨÍỊÒỎÕÓỌÔỒỔỖỐỘƠỜỞỠỚỢÙỦŨÚỤƯỪỬỮỨỰỲỶỸÝỴ";
    var unsignedChars   = "aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyAAAAAAAAAAAAAAAAADEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYY";
    var pattern = new RegExp("[" + signedChars + "]", "g");
    var result = input.replace(pattern, function (m, key, value) {
        return unsignedChars.charAt(signedChars.indexOf(m));
    });
    return result;
}

function getXmlHttpObj(){
    var xml;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xml=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xml=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xml;
}

function loadCaptchaView(){
    var text = " <form method=\"post\">" +
    +  "<img src=\"http://localhost:8084/XMLProject/CaptchaServlet\">" +
    +  "<input id=\"txtcaptcha\" class=\"captcha-input\" type=\"text\"/><br>" +
    +  "<input type=\"submit\" value=\"submit\"/>" +
    +  "</form>"
    return text;
}